package com.flyu.servlet.provider;

import com.alibaba.fastjson.JSONArray;
import com.flyu.pojo.Bill;
import com.flyu.pojo.Provider;
import com.flyu.pojo.User;
import com.flyu.service.bill.BillServiceImpl;
import com.flyu.service.provider.ProviderServiceImpl;
import com.flyu.util.Constants;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProviderServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method.equals("query") && method != null){
            this.query(req, resp);
        } else if (method.equals("add") && method != null){
            this.addProvider(req, resp);
        } else if (method.equals("delprovider") && method != null){
            this.delProvider(req, resp);
        } else if (method.equals("modify") && method != null){
            this.getProviderById(req, resp, "providermodify.jsp");
        } else if (method.equals("view") && method != null){
            this.getProviderById(req, resp, "providerview.jsp");
        } else if (method.equals("modifyexe") && method != null){
            this.modifySave(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    // 供应商列表
    public void query(HttpServletRequest req, HttpServletResponse resp){
        String queryProCode = req.getParameter("queryProCode");
        String queryProName = req.getParameter("queryProName");
        ProviderServiceImpl providerService = new ProviderServiceImpl();

        int pageSize = 5;
        int currentPageNo = 1;
        String pageIndex = req.getParameter("pageIndex");
        int totalCount = providerService.getProviderCount(queryProCode, queryProName);
        int totalPageCount = (totalCount / pageSize) + 1;

        if (pageIndex != null){
            currentPageNo = Integer.parseInt(pageIndex);
        }

        List<Provider> providerList = providerService.getProviderListByRule(queryProCode, queryProName, currentPageNo, pageSize);
        req.setAttribute("providerList", providerList);
        req.setAttribute("queryProCode", queryProCode);
        req.setAttribute("queryProName", queryProName);
        // 显示页数
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.setAttribute("totalPageCount", totalPageCount);
        try {
            req.getRequestDispatcher("providerlist.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 添加供应商
    public void addProvider(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String proCode = req.getParameter("proCode");
        String proName = req.getParameter("proName");
        String proContact = req.getParameter("proContact");
        String proPhone = req.getParameter("proPhone");
        String proAddress = req.getParameter("proAddress");
        String proFax = req.getParameter("proFax");
        String proDesc = req.getParameter("proDesc");
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        User user = (User) o;

        Provider provider = new Provider();
        provider.setProCode(proCode);
        provider.setProName(proName);
        provider.setProContact(proContact);
        provider.setProPhone(proPhone);
        provider.setProFax(proFax);
        provider.setProAddress(proAddress);
        provider.setProDesc(proDesc);
        provider.setCreatedBy(user.getId());
        provider.setCreationDate(new Date());

        ProviderServiceImpl providerService = new ProviderServiceImpl();
        boolean flag = providerService.addProvider(provider);
        if (flag) {
            resp.sendRedirect(req.getContextPath()+"/jsp/provider.do?method=query");
        }else {
            req.getRequestDispatcher("provideradd.jsp").forward(req, resp);
        }

    }
    // 删除供应商
    public void delProvider(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String proid = req.getParameter("proid");
        ProviderServiceImpl providerService = new ProviderServiceImpl();

        Map<String, String> resultMap = new HashMap<String, String>();
        // 四种情况：1.不存在 2.成功 3. 失败 4. 有级联不能删除
        if ((providerService.getProviderById(Integer.parseInt(proid))) == null){
            // 不存在
            resultMap.put("delResult", "notexist");
        }else {
            // 存在
            List<Bill> billList = new BillServiceImpl().getBillByProid(Integer.parseInt(proid));    // 判断供应商是否有级联订单
            int len = 0;
            for (Bill bill : billList) {    // 统计级联个数
                len++;
            }
            if (len > 0){  // billList不为空，说明有级联
                resultMap.put("delResult", String.valueOf(len));
            } else{ // 没有级联
                boolean flag = providerService.delProvider(Integer.parseInt(proid));
                if (flag){
                    resultMap.put("delResult", "true");
                } else {
                    resultMap.put("delResult", "false");
                }
            }
        }
        // 将resultMap传递给前端
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }
    // 根据id查询provider
    public void getProviderById(HttpServletRequest req, HttpServletResponse resp, String url) throws ServletException, IOException {
        String proid = req.getParameter("proid");
        if (!StringUtils.isNullOrEmpty(proid)){
            int pid = Integer.parseInt(proid);
            ProviderServiceImpl providerService = new ProviderServiceImpl();
            Provider provider = providerService.getProviderById(pid);
            req.setAttribute("provider", provider);
            req.getRequestDispatcher(url).forward(req, resp);
        }
    }
    // 保存修改
    public void modifySave(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String proCode = req.getParameter("proCode");
        String proName = req.getParameter("proName");
        String proContact = req.getParameter("proContact");
        String proPhone = req.getParameter("proPhone");
        String proAddress = req.getParameter("proAddress");
        String proFax = req.getParameter("proFax");
        String proDesc = req.getParameter("proDesc");
        Provider provider = new Provider();
        provider.setProCode(proCode);
        provider.setProName(proName);
        provider.setProContact(proContact);
        provider.setProPhone(proPhone);
        provider.setProAddress(proAddress);
        provider.setProFax(proFax);
        provider.setProDesc(proDesc);
        ProviderServiceImpl providerService = new ProviderServiceImpl();
        boolean flag = providerService.modifySave(provider);
        System.out.println("ProviderServlet-->modifySave:"+flag);
        if (flag){
            resp.sendRedirect(req.getContextPath()+"/jsp/provider.do?method=query");
        }else {
            req.getRequestDispatcher("providermodify.jsp").forward(req, resp);
        }
    }
}
